'use strict';
const db = uniCloud.database()
const $ = db.command.aggregate
const dbCmd = db.command
exports.main = async (event, context) => {
	//event为客户端上传的参数 Data  评论内容  评论id       次评论id   是否子回复
	const { user_id, article_id, content, comment_id='', reply_id="" ,isReply} = event
	
	let user = await db.collection("user").doc(user_id).get()
	user = user.data[0]
	
	// 获取文章
	const article = await db.collection("article").doc(article_id).get();
	const comments = article.data[0].comments;
	// 获取下面的评论
	
	let commentOBJ = {
		comment_id: getID(5),
		comment_content:content,
		create_time: new Date().getTime(),
		is_reply:isReply,
		author:{
			author_id:user._id,
			author_name: user.author_name,
			avator:user.avatar,
			professional: user.professional,  // 专业
		},
		replys:[], // 回复
	}
	// 评论文章
	
	
	if(comment_id===''){
		commentOBJ = dbCmd.unshift(commentOBJ)
	} else { // 评论 文章下面的评论
	// 获取评论索引
	let commentIndex = comments.findIndex(item=>item.comment_id === comment_id)
	// 获取作者信息
	let commentAuthor=""
	if(isReply){ // 子回复
	
		commentAuthor = comments[commentIndex].replys.find(item=>item.comment_id === reply_id)
	// console.log(reply_id,comments[commentIndex].replys,'commentscommentscommentscomments');
	}else{  // 主回复
		commentAuthor = comments.find(item=>item.comment_id === comment_id)
	}
	// console.log(commentAuthor,"commentAuthorcommentAuthor");
		commentAuthor = commentAuthor.author.author_name
		commentOBJ.to = commentAuthor
		// 更新回复信息
		commentOBJ = {
			[commentIndex]:{
				replys: dbCmd.unshift(commentOBJ)
			}
		}
		
	}
	
	const res = await db.collection("article").doc(article_id).update({
		comments: commentOBJ
	})
	
	//返回数据给客户端
	return {
		status: 200,
		msg: '回复成功',
		data:res
		}
};


// 生成comment_idid值
function getID(length){
	return Number(Math.random().toString().substr(3,length) + Date.now()).toString(36)
}